/**
 *  MaWeRe - Makes the Web Readable !    
 *  
 *  MaWeRe Bookmarklet is a Structmedia Experiment.                                       
 *  Copyright (c) 2011 Structmedia     
 *  Website: http://www.mawere.com/
 *  Source:  http://code.google.com/p/mawere
 *  Version: 0.9
 *                                                                          
 *  Requires jQuery 1.4.4 or newer (included in source)                     
 *                                                                          
 *  For the content extraction is used the readability javascript by Arc90 Inc                      
 *  http://lab.arc90.com/experiments/readability         
 * 
 *  Most of the icons used in this bookmarklet are from:
 *  http://gentleface.com/free_icon_set.html         
 *                                                                          
 *  Licensed under the Apache License, Version 2.0 (the "License");         
 *  you may not use this file except in compliance with the License.        
 *  You may obtain a copy of the License at                                 
 *                                                                          
 *     http://www.apache.org/licenses/LICENSE-2.0                           
 *                                                                          
 *  Unless required by applicable law or agreed to in writing, software     
 *  distributed under the License is distributed on an "AS IS" BASIS,       
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and     
 *  limitations under the License.                                           
 */

// User Agend detection
var userAgent = navigator.userAgent.toLowerCase();
var isAndroid = (userAgent.search("android") > -1)?true:false;
var isChrome = (userAgent.search("chrom") > -1)?true:false;
var isFirefox = (userAgent.search("firefox") > -1)?true:false;
var isIPad = (userAgent.search("ipad") > -1)?true:false;
var isIPhone = (userAgent.search("iphone") > -1)?true:false;

// Configuration variables needed by readability
var readConvertLinksToFootnotes = false; // 
var readSize = 'size-medium'; // Needed by readability
var readStyle = 'style-novel';  // Needed by readability
var readMargin = 'margin-x-narrow';  // Needed by readability    

// Some configuration arrays
var mawereSizes = new Array('mawere-m', 'mawere-l', 'mawere-xl', 'mawere-s');
var mawereFonts = new Array('mawere-serif', 'mawere-sansserif', 'mawere-console');
var mawereColors = new Array('mawere-white', 'mawere-black', 'mawere-blue');
var mawereMargins = new Array('mawere-xnarrow', 'mawere-narrow', 'mawere-medium', 'mawere-wide');


function generateBookmarklet() {
   alert("javascript:(function(){"+
  "jqueryScript=document.createElement('script');jqueryScript.type='text/javascript';jqueryScript.src='http://mawere.com/mbl/jquery-1.4.4.min.js';document.documentElement.appendChild(jqueryScript);"+
  "mawereScript=document.createElement('script');mawereScript.type='text/javascript';mawereScript.src='http://mawere.com/mbl/mawere.js?x='+(Math.random());document.documentElement.appendChild(mawereScript);"+
  "readabilityScript=document.createElement('script');readabilityScript.type='text/javascript';readabilityScript.src='http://mawere.com/mbl/readability.js?x='+(Math.random());document.documentElement.appendChild(readabilityScript);"+
  "evernoteScript=document.createElement('script');evernoteScript.type='text/javascript';evernoteScript.src='http://static.evernote.com/noteit.js';document.documentElement.appendChild(evernoteScript);"+
  "mawereCss=document.createElement('link');mawereCss.rel='stylesheet';mawereCss.href='http://mawere.com/mbl/mawere.css?x='+(Math.random());mawereCss.type='text/css';mawereCss.media='all';document.documentElement.appendChild(mawereCss);" +
  "mawereSize='"+mawereSize+"';"+
  "mawereFont='"+mawereFont+"';"+
  "mawereColor='"+mawereColor+"';"+ 
  "mawereMargin='"+mawereMargin+"';"+
  "})()");
} 

var devMode = (devMode==null)?false:devMode;

var mawereSize = (mawereSize==null)?mawereSizes[0]:mawereSize;
var mawereFont = (mawereFont==null)?mawereFonts[0]:mawereFont;
var mawereColor = (mawereColor==null)?mawereColors[0]:mawereColor;
var mawereMargin = (mawereMargin==null)?mawereMargins[0]:mawereMargin;

function initStyles() {
  $('body').attr('class', '');
  $('#readInner').attr('class', '');
  $('#readInner').addClass(mawereSize);
  $('#readInner').addClass(mawereFont);
  $('#readInner').addClass(mawereMargin);    
  $('body').addClass(mawereColor);
}

function toggleSize() {  
    $('#readInner').removeClass(mawereSize);   
    var currentIndex = mawereSizes.indexOf(mawereSize);
    var nextIndex = currentIndex+1;
    if (nextIndex >= mawereSizes.length) { nextIndex = 0; }    
    mawereSize = mawereSizes[nextIndex];
    $('#readInner').addClass(mawereSize);
}

function toggleFont() {  
    $('#readInner').removeClass(mawereFont);   
    var currentIndex = mawereFonts.indexOf(mawereFont);
    var nextIndex = currentIndex+1;
    if (nextIndex >= mawereFonts.length) { nextIndex = 0; }    
    mawereFont = mawereFonts[nextIndex];
    $('#readInner').addClass(mawereFont);
}

function toggleMargin() {  
    $('#readInner').removeClass(mawereMargin);   
    var currentIndex = mawereMargins.indexOf(mawereMargin);
    var nextIndex = currentIndex+1;
    if (nextIndex >= mawereMargins.length) { nextIndex = 0; }    
    mawereMargin = mawereMargins[nextIndex];
    $('#readInner').addClass(mawereMargin);
}

function toggleColor() {  
    $('body').removeClass(mawereColor);   
    var currentIndex = mawereColors.indexOf(mawereColor);
    var nextIndex = currentIndex+1;
    if (nextIndex >= mawereColors.length) { nextIndex = 0; }    
    mawereColor = mawereColors[nextIndex];
    $('body').addClass(mawereColor);
}

// Generating MaWeRe UI
var mawereDiv  = document.createElement("DIV"); // This div-element is included later by the mawere script
mawereDiv.id        = "mawereBody";
mawereDiv.innerHTML = '' +
'<div id="mawerePrev"></div>'+    
'<div id="mawereNext"></div>'+   
'<div id="mawereActivate"></div>'+
'<div id="mawereMenu">'+
  '<div id="mawereColors">&nbsp;</div>'+
  '<div id="mawereFont">&nbsp;</div>'+
  '<div id="mawereSize">&nbsp;</div>'+
  '<div id="mawereMargin">&nbsp;</div>'+
  '<div id="mawereSave">&nbsp;</div>'+
  '<div id="mawereImages">&nbsp;</div>'+  
  '<div id="mawereEvernote">&nbsp;</div>'+
  '<div id="mawereTwitter">&nbsp;</div>'+
  '<div id="mawereFacebook">&nbsp;</div>'+
  '<div id="mawereAbout">&nbsp;</div>'+
  '<div id="mawerePrint">&nbsp;</div>'+
  '<div id="mawereClose">&nbsp;</div>'+
'</div>'+ 
 '';

// Date Object needed by the footer
var now = new Date();
var mawereFooter = document.createElement("DIV");
mawereFooter.id        = "mawereFooter";
mawereFooter.innerHTML = '<hr />' +
  '<div id="">Extracted from: <a href="'+document.location+'">'+document.location+'</a> on '+(1900+now.getYear())+'-'+(1+now.getMonth())+'-'+now.getDate()+'</div>' +
  '<div id="mawereFooter-left" style="float: left;">' +
    'MaWeRe Bookmarklet - a STRUCTmedia experiment&nbsp; <a href="http://www.mawere.com">www.mawere.com</a>' +
  '</div>' +
  '<!--div id="mawereFooter-right" style="float: right;">' +
    '<a href="http://www.twitter.com/ilianste">Follow us on Twitter</a>' +
  '</div-->' + 
 '';
 
var scrollby = window.innerHeight - 20;
function pageScrollDown() {   window.scrollBy(0, scrollby); }

function pageScrollUp() {   window.scrollBy(0, -scrollby); } 

function enableEventHandling() {
  $(document).ready(function(){        
    $("#mawereActivate").click( function() {
      $("#mawereMenu").show();  
      $("#mawereActivate").css("background-image","none");      
      $("#mawereActivate").hide();        
    });  
    
    $("#mawereClose").click( function() {      
      $("#mawereMenu").hide();
      $("#mawereActivate").show();          
    });    

    $("#mawereColors").click( function() {
      toggleColor();
    });     

    $("#mawereSize").click( function() {
      toggleSize();  
    });   
        
    $("#mawereFont").click( function() {
      toggleFont(); 
    }); 

    $("#mawereMargin").click( function() {
      toggleMargin();
    }); 
        
    $("#mawereEvernote").click( function() {
      Evernote.doClip({contentId:'readInner',code:'Ilia8863'});
    });   

    $("#mawereFacebook").click( function() {
      if(confirm("You are about to leave this page. \nDo you want to continue?")) {
        window.location.href="http://www.facebook.com/sharer.php?u="+encodeURIComponent(document.location);
      }  
    });   

    $("#mawereTwitter").click( function() {
      if(confirm("You are about to leave this page. \nDo you want to continue?")) {      
        window.location.href="http://twitter.com/share?url="+encodeURIComponent(document.location);
      }
    });
    
    $("#mawereSave").click( function() {
      generateBookmarklet();
    });  
    
    $("#mawereImages").click( function() {
      alert("Not implemented yet!");
    }); 
    
    $("#mawereAbout").click( function() {
      if(confirm("You are about to leave this page. \nDo you want to continue?")) {
        window.location.href="http://mawere.com";        
      }
    });     
                
    $("#mawerePrint").click( function() {
      $("#mawereMenu").hide();
      $("#mawereActivate").show();          
      $("#mawerePrev").css("background-image","none");       
      $("#mawereNext").css("background-image","none");                   
      window.print(); 
    });       
    
    $("#readInner").click( function() {
      $("#mawereMenu").hide();  
      $("#mawereActivate").show();        
    });    

    $("#mawerePrev").click( function() {
      $("#mawereMenu").hide();  
      $("#mawereActivate").show();
      $("#mawerePrev").css("background-image","none");                 
      pageScrollUp();
    });
      
    $("#mawereNext").click( function() {
      $("#mawereMenu").hide();  
      $("#mawereActivate").show();  
      $("#mawereNext").css("background-image","none");               
      pageScrollDown();
    });    
    
  });  
  
}
 
function initMaWeRe() { 
  var meta = document.createElement('meta');
  meta.name = "viewport";
  meta.content = "initial-scale=1.0, maximum-scale=1.0, user-scalable=no, width=device-width";
  document.getElementsByTagName('head').item(0).appendChild(meta);
  
  document.body.insertBefore(mawereDiv, document.body.firstChild);  
  $('#readInner').after(mawereFooter);

  if(!devMode) {
     $("#mawereSave").remove();    
     $("#mawereImages").remove();                 
  }
  
  $("#readTools").remove(); 
  $("#readFooter").remove(); 
  
  // Disable some functionality on mobile devices(Android & iPhone)
  if(isAndroid || isIPhone || isIPad) {
     $("#mawerePrint").remove();      
     $("#mawereMargin").remove();      
  }      

  // Set initial styling 
  initStyles();

  // changing the scrolling distance after rotating the device or resizing the browser window
  $(window).resize(function() {
    scrollby = window.innerHeight - 20;
  });

  // Disable UI on iphone and ipad
  if(!isIPhone && !isIPad) { 
    enableEventHandling();
  }  
}

// Initilise MaWeRe only after readabilty initialisation
if(readability != null) { 
  initMaWeRe();  
}